package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lwk
 * @since 2025-6-5
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private BlockingQueue<VoucherOrder> blockingQueue = new ArrayBlockingQueue<>(1024*1024);

    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrederHandler());
    }


    private class   VoucherOrederHandler implements Runnable{
        @Override
        public void run() {
            while (true){
                //1.获取队列中的订单信息
                try {
                    VoucherOrder voucherOrder = blockingQueue.take();
                    //2.创建订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                   log.error("订单异常",e);
                }

            }

        }

        private void handleVoucherOrder(VoucherOrder voucherOrder) {
            //获取用户id
            Long userId = voucherOrder.getUserId();
            //创建锁对象
            SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
           //获取锁
           boolean isLock = lock.tryLock(1200);
            if (!isLock) {
              //获取锁失败，返回失败
           log.error("不允许重复下单");
           return;
        }
        try {
             proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }


        }
    }

    private  IVoucherOrderService proxy;
    @Override

    public Result seckillVoucher(Long voucherId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT, Collections.emptyList(), voucherId.toString(), userId.toString());
        //2.判断结果是否为0
        if (result.intValue() !=0){
            //2.1不为0，没有购买资格
            return Result.fail(result.intValue() == 1 ? "库存不足" : "不能重复下单");
        }
        //2.2为0，购买资格.把下单信息保存到阻塞队列
        VoucherOrder voucherOrder=new VoucherOrder();
        //订单id
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        // 用户id
        voucherOrder.setUserId(userId);
        // 代金卷id;
        voucherOrder.setVoucherId(voucherId);
        //创建阻塞队列
        blockingQueue.add(voucherOrder);
        //获取代理对象（事务）
       proxy = (IVoucherOrderService) AopContext.currentProxy();
        //.返回订单id
        return  Result.ok(orderId);
    }



//    @Override
//    @Transactional
//    public Result seckillVoucher(Long voucherId) {
//        //根据id查询秒杀优惠卷信息
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//
//        //判断时间是否开始
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("秒杀尚未开始");
//        }
//        ;
//        //判断时间是否结束
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀已结束");
//        }
//        //判断库存是否充足
//        if (seckillVoucher.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
//        //创建锁对象
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//
//        //获取锁
//        boolean isLock = lock.tryLock(1200);
//        if (!isLock) {
//            //获取锁失败，返回失败
//            return Result.fail("不允许重复下单");
//        }
//        try {
//            //获取代理对象（事务）
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
//
//    }

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //判断一人一单
        Long userId = voucherOrder.getUserId();

            int count = query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count();
            if (count > 0) {
                //用户已经购买过了
               log.error("用户已经购买过了");
               return;
            }

            //扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock - 1")//set stock = stock - 1
                    .eq("voucher_id", voucherOrder.getVoucherId()) //where id=?
                    .gt("stock", 0) //and  stock >0
                    .update();

            if (!success) {
                log.error("库存不足");
                return;
            }

            //写入数据库
            save(voucherOrder);
    }
}